<template>
	<div>
		<CustomDialog
			:title="state.dialog.title"
			v-model:visible="state.dialog.isShowDialog"
			dialogWidth="900px"
			@close="closeDialog"
			:dialogFooterBtn="true"
		>
			<div class="layout-padding-auto layout-scroll-padding">
				<div class="search mb15">
					<el-row :gutter="10">
						<el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
							<el-form-item label="活动名称:">
								<el-input v-model="state.search.name" size="default" clearable placeholder="请输入活动名称" style="width: 100%"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" v-show="state.isToggle">
							<el-form-item label="创建时间:">
								<el-date-picker
									type="datetimerange"
									v-model="state.search.searchDateTime"
									start-placeholder="创建开始时间"
									end-placeholder="创建时间"
									style="width: 100%"
								/>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8">
							<el-form-item class="table-form-btn" label-width="10px">
								<div class="table-form-btn-toggle ml10 cursor-pointer" @click="state.isToggle = !state.isToggle">
									<span>{{ state.isToggle ? '收筛选' : '展筛选' }}</span>
									<SvgIcon :name="state.isToggle ? 'ele-ArrowUp' : 'ele-ArrowDown'" />
								</div>
								<el-button size="default" type="primary" class="ml10" @click="getTableData">
									<el-icon>
										<ele-Search />
									</el-icon>
									查询
								</el-button>
							</el-form-item>
						</el-col>
					</el-row>
					<el-table :data="state.tableData.data" @selection-change="handleSelectionChange" v-loading="state.tableData.loading" style="width: 100%">
						<el-table-column type="selection" width="55" />
						<el-table-column prop="groupName" label="活动名称" show-overflow-tooltip></el-table-column>
						<el-table-column prop="joinActivityCounts" label="参与商品" show-overflow-tooltip></el-table-column>

						<el-table-column prop="activityStatus" label="活动状态" show-overflow-tooltip>
							<template #default="scope">
								<el-tag v-if="scope.row.activityStatus == 0">未开始</el-tag>
								<el-tag v-else-if="scope.row.activityStatus == 1" type="warning">进行中</el-tag>
								<el-tag v-else type="error">结束</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="groupStartTime" label="活动开始时间" show-overflow-tooltip></el-table-column>
						<el-table-column prop="groupEndTime" label="活动结束时间" show-overflow-tooltip></el-table-column>
						<el-table-column prop="updateTime" label="修改时间" show-overflow-tooltip></el-table-column>
						<el-table-column prop="updateUsername" label="操作人" show-overflow-tooltip></el-table-column>
						<el-table-column label="操作" width="100">
							<template #default="scope">
								<el-button :disabled="scope.row.roleName === '超级管理员'" size="small" text type="primary" @click="onChoice(scope.row)"
									>选择
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<el-pagination
					@size-change="onHandleSizeChange"
					@current-change="onHandleCurrentChange"
					:page-sizes="[10, 15, 20, 30, 50, 100]"
					v-model:current-page="state.tableData.paging.currentPage"
					background
					v-model:page-size="state.tableData.paging.pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="state.tableData.paging.totalCount"
				>
				</el-pagination>
			</div>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="closeDialog" size="default">取 消</el-button>
					<el-button type="primary" @click="onBatchChoice" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</CustomDialog>
	</div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { GroupApi } from '/@/api/shop/group/index';
import { resolveStartTime, resolveEndTime } from '/@/views/shop/activity/utils';
import { ElMessage, ElMessageBox } from 'element-plus';
import messageUtils from '/@/utils/messageUtils';
const emits = defineEmits(['choice']);
const state = reactive({
	isToggle: false,
	search: {
		name: '',
		searchDateTime: '',
	},
	tableData: {
		data: [],
		total: 0,
		loading: false,
		paging: {
			currentPage: 1,
			pageSize: 15,
			totalCount: 0,
			totalPages: 0,
		},
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '选择拼团',
		submitTxt: '确认',
	},
});

let cgs: ChoiceGroup[] = [];

const onRefresh = () => {
	onHandleCurrentChange(1);
};

const onRowDel = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除团购活动名称：“${row.groupName}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await GroupApi().delete(row.id);
			getTableData();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

// 分页改变
const onHandleSizeChange = (pageSize: number) => {
	state.tableData.paging.pageSize = pageSize;
	getTableData();
};
// 分页改变
const onHandleCurrentChange = (currentPage: number) => {
	state.tableData.paging.currentPage = currentPage;
	getTableData();
};

const getTableData = async () => {
	state.tableData.loading = true;
	try {
		const { data } = await GroupApi().search({
			groupName: state.search.name,
			startTime: resolveStartTime(state.search.searchDateTime),
			endTime: resolveEndTime(state.search.searchDateTime),
			offset: (state.tableData.paging.currentPage - 1) * state.tableData.paging.pageSize,
			limit: state.tableData.paging.pageSize,
		});
		state.tableData.data = data.datas;
		state.tableData.paging.currentPage = data.paging.currentPage;
		state.tableData.paging.totalCount = data.paging.totalCount;
		console.log('data: ', data);
	} catch (e) {
		messageUtils().error('加载失败，请重试');
	} finally {
		state.tableData.loading = false;
	}
};

const onChoice = (row: any) => {
	let cg: ChoiceGroup = { groupId: row.id };
	emits('choice', [cg]);
	closeDialog();
};

const onBatchChoice = () => {
	emits('choice', cgs);
	closeDialog();
};

const onOpen = () => {
	getTableData();
	state.dialog.isShowDialog = true;
};

const closeDialog = () => {
	state.dialog.isShowDialog = false;
	cgs = [];
};

const handleSelectionChange = (val: any[]) => {
	cgs = [];
	val.forEach((e) => {
		cgs.push({ groupId: e.id });
	});
};

defineExpose({ onOpen });
</script>

<style scoped lang="scss">
.search {
	background-color: white;
	padding: 0 16px;
}

.table-form-btn-toggle {
	white-space: nowrap;
	user-select: none;
	display: flex;
	align-items: center;
	color: var(--el-color-primary);
}
</style>
